<template>
	<view class="order-detail-container">
		<!-- 订单状态模块 -->
		<view class="order-status">
			<view class="status-text">当前状态：
				<text class="main-status"
					:style="{ color: statusColor }">{{ orderStatusList[dataJson.order_status] }}</text>
				<!-- <text class="sub-status">{{ statusDesc }}</text> -->
			</view>
		</view>

		<!-- 订单基本信息 -->
		<view class="order-info">
			<view class="info-item">
				<text class="label">订单编号：</text>
				<text class="value">{{ orderNo }}</text>
			</view>
			<view class="info-item">
				<text class="label">下单时间：</text>
				<text class="value">{{ dataJson.add_time }}</text>
			</view>
			<view class="info-item">
				<text class="label">订单类型：</text>
				<text class="value">{{ orderType[dataJson.type].name }}</text>
			</view>
			<view class="info-item">
				<text class="label">支付方式：</text>
				<text class="value">{{ dataJson.pay_type }}</text>
			</view>
<!-- 			<view class="info-item" v-if="orderStatus !== '待付款'">
				<text class="label">支付时间：</text>
				<text class="value">{{ payTime }}</text>
			</view> -->
			<view class="info-item" v-if="dataJson.after_sales!=0">
				<text class="label">售后状态：</text>
				<text class="value" style="color: red;">{{service[dataJson.after_sales]}}</text>
			</view>
		</view>

		<!-- 商品列表 -->
		<view class="product-list">
			<view class="product-item" v-for="(product, index) in dataJson.info" :key="index">
				<view class="product-img">
					<image :src="product.thumb" mode="aspectFit"></image>
				</view>
				<view class="product-info">
					<view class="product-name">{{ product.title }}</view>
					<!-- <view class="product-spec">{{ product.spec }}</view> -->
					<view class="product-price">
						<text class="price">¥{{ product.price }}</text>
						<text class="quantity">x{{ product.num }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 配送信息 -->
		<view class="delivery-info" v-if="dataJson.address">
			<view class="info-header">配送信息</view>
			<view class="info-content">
				<!--        <view class="recipient">
          <text class="name">{{ recipient.name }}</text>
          <text class="phone">{{ recipient.phone }}</text>
        </view>
        <view class="address">
          {{ recipient.address }}
        </view> -->

				<view class="delivery-method">
					<text class="label">姓名：</text>
					<text class="value">{{ dataJson.address.name }}</text>
				</view>

				<view class="delivery-method">
					<text class="label">手机号：</text>
					<text class="value">{{ dataJson.address.mobile }}</text>
				</view>

				<view class="delivery-method">
					<text class="label">地址：</text>
					<text
						class="value">{{ dataJson.address.province }}{{ dataJson.address.city }}{{ dataJson.address.area }}{{ dataJson.address.address }}</text>
				</view>

				<!-- 	 <view class="delivery-method"
		    <text class="label">姓名：</text>
		    <text class="value">{{ dataJson.address.mobile }}</text>
		  </view>
		  <view class="delivery-method"
		     <text class="label">地址：</text>
		     <text class="value">{{ dataJson.address.province }}{{ dataJson.address.city }}{{ dataJson.address.area }}{{ dataJson.address.address }}</text>
		   </view> -->
			</view>
		</view>

		<!-- 价格信息 -->
		<view class="price-info" v-if="dataJson.type!=4">
			<view class="info-header">价格详情</view>
			<view class="price-item">
				<text class="label">商品总价：</text>
				<text class="value">¥{{ dataJson.goods_amount }}</text>
			</view>
			<view class="price-item">
				<text class="label">运费：</text>
				<text class="value">¥{{ dataJson.fare }}</text>
			</view>
			<!--   <view class="price-item" v-if="couponAmount > 0">
        <text class="label">优惠券：</text>
        <text class="value">-¥{{ couponAmount }}</text>
      </view>
      <view class="price-item" v-if="discountAmount > 0">
        <text class="label">商品折扣：</text>
        <text class="value">-¥{{ discountAmount }}</text>
      </view> -->
			<view class="price-item total">
				<text class="label">实付款：</text>
				<text class="value">¥{{ dataJson.price }}</text>
			</view>
		</view>

		<!-- 订单操作按钮组 -->
	<!-- 	<view class="order-actions" v-if="actionButtons.length > 0">
			<button v-for="(button, index) in actionButtons" :key="index" :class="button.type"
				v-if="button.action!='applyAfterSales'" @click="handleAction(button.action)">
				{{ button.text }}
			</button>
			<button v-for="(button, index) in actionButtons" :key="index" :class="button.type"
				v-if="button.action=='applyAfterSales'&&dataJson.after_sales==0&&dataJson.type==1" @click="handleAction(button.action)">
				{{ button.text }}
			</button>
		</view> -->
	<!-- 	<uni-popup ref="popup" background-color="#fff">
			<view class="popup-content" :class="{ 'popup-height': type === 'left' || type === 'right' }">
				<h3>退货地址</h3>
				<div class="items">
					{{dataJson.tui_address.name}} {{dataJson.tui_address.mobile}}
				</div>
				<div class="items">{{dataJson.tui_address.address}}</div>
				<h3 class="h3-1">输入退货快递单号</h3>
				<div class="items">
					<input type="text" v-model="inputVal" placeholder="请输入单号" />
				</div>
				<div class="items">
					<textarea name="" id="" v-model="msgVal" placeholder="请输入理由"></textarea>
				</div>
				<button class="btn" @tap="toAfterSeles">提交申请</button>
			</view>
		</uni-popup> -->
	</view>
</template>

<script>
	import {
		request
	} from '@/utils/request.js'
	export default {

		data() {
			return {
				service:['未发起','售后已申请','已退款','拒绝'],
				msgVal: '',
				inputVal: '',
				dataJson: {
					info: []
				},
				orderId: null,
				// 订单状态配置（待付款、待发货、已发货、已完成、已关闭）
				orderStatus: '待付款', // 动态状态，实际应从接口获取
				orderStatusList: ['', '待付款', '待发货', '已发货', '已完成', '已关闭'],
				orderType: [{},
					{
						name: '普通商品购买'
					},
					{
						name: '加入库存'
					},
					{
						name: '分享赠送'
					},
					{
						name: '仓库配送'
					},
				],
				statusConfig: {
					'1': {
						icon: 'icon-wait',
						color: '#FF5722', // 橙色
						desc: '请在24小时内完成支付',
						showBtn: true,
						operate: '去支付',
						btnType: 'btn-primary'
					},
					'2': {
						icon: 'icon-package',
						color: '#2196F3', // 蓝色
						desc: '商家正在备货中',
						showBtn: true,
						operate: '催促发货',
						btnType: 'btn-primary'
					},
					'3': {
						icon: 'icon-express',
						color: '#4CAF50', // 绿色
						desc: '商品正在运输中',
						showBtn: true,
						operate: '查看物流',
						btnType: 'btn-primary'
					},
					'4': {
						icon: 'icon-success',
						color: '#00B42A', // 深绿色
						desc: '订单已完成，感谢您的购买',
						showBtn: false
					},
					'5': {
						icon: 'icon-close',
						color: '#999', // 灰色
						desc: '订单已关闭，如有问题请联系客服',
						showBtn: false
					}
				},
				// 模拟订单数据（实际应从接口获取）
				orderNo: '20231206143528901',
				orderTime: '2023-12-06 14:35:28',
				payMethod: '微信支付',
				payTime: '2023-12-06 14:36:05',
				products: [{
						id: 1,
						name: 'iPhone 14 Pro 256GB 暗紫色',
						spec: '颜色：暗紫色 | 容量：256GB',
						price: 7999.00,
						quantity: 1,
						image: '/static/product1.jpg'
					},
					{
						id: 2,
						name: 'Apple AirPods Pro (第二代)',
						spec: '无线充电盒',
						price: 1799.00,
						quantity: 1,
						image: '/static/product2.jpg'
					}
				],
				recipient: {
					name: '张三',
					phone: '13800138000',
					address: '北京市朝阳区建国路88号88层8888室'
				},
				deliveryMethod: '顺丰速运',
				trackingNumber: 'SF1234567890123',
				// 价格信息
				totalPrice: 9798.00,
				// shippingFee: 0.00,
				// couponAmount: 200.00,
				// discountAmount: 798.00,
				// 动态状态变量
				statusIcon: '',
				statusColor: '',
				statusDesc: '',
				showOperateBtn: false,
				operateText: '',
				btnType: '',
				// 底部操作按钮配置
				actionButtons: []
			};
		},
		onLoad(options) {
			console.log(options)
			// 实际项目中应通过options获取订单ID，然后调用接口获取订单详情
			// 这里使用模拟数据
			if (options.id) {
				this.orderId = options.id
			}
			this.getInfo()
		},
		methods: {
			toAfterSeles() {
				let params = {
					oid: this.dataJson.id,
					msg: this.msgVal,
					sn: this.inputVal
				}
				if(!params.sn){
						uni.showToast({
							title: '请输入退货快递单号',
							icon: 'none'
						})
					return
				}
				if(!params.msg){
						uni.showToast({
							title: '请输入退货说明',
							icon: 'none'
						})
					return
				}
				request({
					url: 'order/order-refund',
					method: 'post',
					data:params
				}).then(res => {
					this.$refs.popup.close()
					console.log(1,res)
					if (res.status == 200) {
						console.log(res.data)
						this.dataJson.after_sales=1
					}else{
						uni.showToast({
							title: res.message,
							icon: 'none'
						})
					}
				}).catch(err=>{
					console.log(2,err)
					uni.showToast({
						title: err.message,
						icon: 'none'
					})
				})
				console.log(params)
			},
			getInfo() {
				request({
					url: 'order/order-info',
					method: 'get',
					data: {
						id: this.orderId

					}
				}).then(res => {
					if (res.status == 200) {
						console.log(res.data)
						this.dataJson = res.data
						this.initStatus();
						this.initActionButtons();
						// this.selectedGoods = res.data.list
					} else {
						console.log(res)
						uni.hideLoading()
						uni.showToast({
							title: res.message,
							icon: 'none'
						})
					}
				})
			},
			// 初始化订单状态
			initStatus() {
				const {
					orderStatus,
					statusConfig,
					dataJson
				} = this;
				const config = statusConfig[dataJson.order_status];
				// this.statusIcon = config.icon;
				this.statusColor = config.color;
				this.statusDesc = config.desc;
				this.showOperateBtn = config.showBtn || false;
				this.operateText = config.operate || '';
				this.btnType = config.btnType || '';
			},
			// 初始化底部操作按钮
			initActionButtons() {
				const buttons = [];
				switch (this.dataJson.order_status) {
					case 1:
						buttons.push({
							text: '取消订单',
							type: 'btn-outline',
							action: 'cancelOrder'
						}, {
							text: '立即支付',
							type: 'btn-primary',
							action: 'payNow'
						});
						break;
					case 2:
						buttons.push({
								text: '取消订单',
								type: 'btn-outline',
								action: 'cancelOrder'
							},
							// { text: '联系客服', type: 'btn-primary', action: 'contactService' }
						);
						break;
					case 3:
						buttons.push({
								text: '确认收货',
								type: 'btn-outline',
								action: 'confirmReceipt'
							},
							// { text: '查看物流', type: 'btn-primary', action: 'viewLogistics' }
						);
						break;
					case 4:
						buttons.push({
								text: '申请售后',
								type: 'btn-outline',
								action: 'applyAfterSales'
							},
							// { text: '评价商品', type: 'btn-primary', action: 'evaluateProduct' }
						);
						break;
					case 5:
						buttons.push({
								text: '删除订单',
								type: 'btn-outline',
								action: 'deleteOrder'
							},
							// { text: '联系客服', type: 'btn-primary', action: 'contactService' }
						);
						break;
				}
				console.log()
				this.actionButtons = buttons;
			},
			// 处理状态操作按钮点击
			handleStatusOperate() {
				switch (this.orderStatus) {
					case '1':
						this.payNow();
						break;
					case '2':
						this.urgeShipping();
						break;
					case '3':
						this.viewLogistics();
						break;
				}
			},
			// 处理底部操作按钮点击
			handleAction(action) {
				this[action]();
			},
			// 导航返回
			goBack() {
				uni.navigateBack();
			},
			// 支付相关
			//    payNow() {
			//    },
			payNow(order_sn) {
				request({
					url: 'user/pay',
					method: 'post',
					data: {
						order_sn: this.dataJson.order_num
					}
				}).then(res => {
					if (res.status == 200) {
						console.log(res)
						this.pay(res.data)
					} else {
						console.log(res)
						uni.hideLoading()
						uni.showToast({
							title: res.message,
							icon: 'none'
						})
					}
				})
			},
			pay(payParams) {
				let that = this;
				// 修正参数名并转换类型
				const paymentParams = {
					appId: String(payParams.appId),
					timeStamp: String(payParams.timeStamp), // 关键修正：从 timesTamp 取值
					nonceStr: String(payParams.nonceStr),
					package: String(payParams.package),
					signType: String(payParams.signType),
					paySign: String(payParams.paySign)
				};

				// 检查必需参数
				const requiredParams = ['appId', 'timeStamp', 'nonceStr', 'package', 'signType', 'paySign'];
				const missingParams = requiredParams.filter(param => !paymentParams[param]);

				if (missingParams.length > 0) {
					console.error('缺少支付参数:', missingParams);
					uni.showToast({
						title: '支付参数缺失',
						icon: 'none'
					});
					return;
				}

				console.log('修正后的支付参数:', paymentParams);
				// 调起支付
				uni.requestPayment({
					timeStamp: paymentParams.timeStamp,
					nonceStr: paymentParams.nonceStr,
					package: paymentParams.package,
					signType: 'MD5',
					paySign: paymentParams.paySign,
					success(res) {
						console.log('支付成功:', res);
						that.dataJson.order_status = 2
						that.initStatus();
						that.initActionButtons();
					},
					fail(res) {
						console.error('支付失败:', res);
						uni.showToast({
							title: '支付失败: ' + res.errMsg,
							icon: 'none'
						});
					}
				});
			},
			// 物流相关
			viewLogistics() {
				uni.navigateTo({
					url: '/pages/logistics/index?trackingNo=' + this.trackingNumber
				});
			},
			// // 订单操作
			// cancelOrder() {
			//   uni.showModal({
			//     title: '确认取消订单',
			//     content: '您确定要取消该订单吗？',
			//     success: (res) => {
			//       if (res.confirm) {
			//         // 调用取消订单接口
			//         uni.showLoading({ title: '处理中...' });
			//         setTimeout(() => {
			//           uni.hideLoading();
			//           uni.showToast({
			//             title: '订单已取消',
			//             icon: 'success',
			//             success: () => {
			//               this.orderStatus = '已关闭';
			//               this.initStatus();
			//               this.initActionButtons();
			//             }
			//           });
			//         }, 1000);
			//       }
			//     }
			//   });
			// },


			cancelOrder(orderId) {
				uni.showModal({
					title: '提示',
					content: '确定要取消该订单吗？',
					success: (res) => {
						uni.showLoading({
							title: '处理中...'
						})
						if (res.confirm) {
							request({
								url: 'order/order-update',
								method: 'post',
								data: {
									oid: this.dataJson.id,
									status: 4
								}
							}).then(res => {
								if (res.status == 200) {

									uni.hideLoading()
									uni.showToast({
										title: '订单已取消'
									})
									this.dataJson.order_status = 5
									this.initStatus();
									this.initActionButtons();
								} else {
									console.log(res)
									uni.hideLoading()
									uni.showToast({
										title: res.message,
										icon: 'none'
									})
								}
							}).catch(err => {
								uni.hideLoading()
							})
						} else {
							uni.hideLoading()
						}
					}
				})
			},

			// confirmReceipt() {
			//   uni.showModal({
			//     title: '确认收货',
			//     content: '确认收到商品后，订单将标记为已完成',
			//     success: (res) => {
			//       if (res.confirm) {
			//         // 调用确认收货接口
			//         uni.showLoading({ title: '处理中...' });
			//         setTimeout(() => {
			//           uni.hideLoading();
			//           uni.showToast({
			//             title: '收货成功',
			//             icon: 'success',
			//             success: () => {
			//               this.orderStatus = '已完成';
			//               this.initStatus();
			//               this.initActionButtons();
			//             }
			//           });
			//         }, 1000);
			//       }
			//     }
			//   });
			// },
			// 确认收货
			confirmReceipt(orderId) {
				uni.showModal({
					title: '提示',
					content: '请确认已收到商品，确认后将完成交易',
					success: (res) => {
						uni.showLoading({
							title: '处理中...'
						})
						if (res.confirm) {
							request({
								url: 'order/order-update',
								method: 'post',
								data: {
									oid: this.dataJson.id,
									status: 3
								}
							}).then(res => {
								if (res.status == 200) {

									uni.hideLoading()
									uni.showToast({
										title: '确认收货成功'
									})
									this.dataJson.order_status = 4
									this.initStatus();
									this.initActionButtons();
								} else {
									console.log(res)
									uni.hideLoading()
									uni.showToast({
										title: res.message,
										icon: 'none'
									})
								}
							}).catch(err => {
								uni.hideLoading()
							})

						} else {
							uni.hideLoading()
						}
					}
				})
			},
			// 客服相关
			contactService() {
				uni.showModal({
					title: '联系客服',
					content: '客服电话：400-123-4567\n是否立即拨打电话？',
					confirmText: '拨打电话',
					cancelText: '在线咨询',
					success: (res) => {
						if (res.confirm) {
							uni.makePhoneCall({
								phoneNumber: '4001234567'
							});
						} else if (res.cancel) {
							uni.navigateTo({
								url: '/pages/customer-service/index'
							});
						}
					}
				});
			},
			// 评价相关
			evaluateProduct() {
				uni.navigateTo({
					url: '/pages/evaluation/index?orderId=' + this.orderNo
				});
			},
			// 售后相关
			applyAfterSales() {
				this.toggle('bottom');
				// uni.navigateTo({ url: '/pages/after-sales/index?orderId=' + this.orderNo });
			},
			toggle(type) {
				this.type = type
				// open 方法传入参数 等同在 uni-popup 组件上绑定 type属性
				this.$refs.popup.open(type)
			},
			// 删除订单
			deleteOrder() {
				uni.showModal({
					title: '确认删除',
					content: '删除后将无法恢复，是否继续？',
					success: (res) => {
						if (res.confirm) {
							// 调用删除订单接口
							uni.showLoading({
								title: '处理中...'
							});
							setTimeout(() => {
								uni.hideLoading();
								uni.showToast({
									title: '订单已删除',
									icon: 'success',
									success: () => {
										setTimeout(() => {
											uni.navigateBack();
										}, 1500);
									}
								});
							}, 1000);
						}
					}
				});
			},
			// 催促发货
			urgeShipping() {
				uni.showToast({
					title: '已通知商家尽快发货',
					icon: 'none'
				});
			}
		}
	};
</script>

<style lang="scss">
	/* 全局样式 */
	page {
		background-color: #f5f5f5;
	}

	/* 导航栏样式 */
	.nav-bar {
		display: flex;
		align-items: center;
		height: 100rpx;
		background-color: white;
		padding: 0 20rpx;
		position: sticky;
		top: 0;
		z-index: 100;
	}

	.nav-back {
		width: 80rpx;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.nav-back .iconfont {
		font-size: 40rpx;
		color: #333;
	}

	.nav-title {
		flex: 1;
		text-align: center;
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
	}

	/* 订单状态模块 */
	.order-status {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx 20rpx;
		background-color: white;
		border-radius: 8rpx;
		margin: 20rpx;
	}

	.status-icon {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
		color: white;
		font-size: 36rpx;
	}

	.status-text {
		flex: 1;
	}

	.main-status {
		font-size: 34rpx;
		font-weight: bold;
		color: #333;
	}

	.sub-status {
		font-size: 28rpx;
		color: #666;
		margin-top: 8rpx;
	}

	.status-btn button {
		padding: 12rpx 24rpx;
		border-radius: 6rpx;
		font-size: 28rpx;
	}

	.btn-primary {
		background-color: #007AFF;
		color: white;
	}

	.btn-outline {
		border: 1rpx solid #007AFF;
		color: #007AFF;
		background-color: white;
	}

	/* 信息模块通用样式 */
	.order-info,
	.product-list,
	.delivery-info,
	.price-info {
		background-color: white;
		border-radius: 8rpx;
		margin: 20rpx;
		overflow: hidden;
	}

	.info-header {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		padding: 25rpx 20rpx;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.info-item {
		display: flex;
		align-items: center;
		padding: 20rpx;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.info-item:last-child {
		border-bottom: none;
	}

	.label {
		font-size: 28rpx;
		color: #666;
		width: 200rpx;
	}

	.value {
		font-size: 28rpx;
		color: #333;
		flex: 1;
	}

	/* 商品列表样式 */
	.product-item {
		display: flex;
		padding: 20rpx;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.product-item:last-child {
		border-bottom: none;
	}

	.product-img {
		width: 160rpx;
		height: 160rpx;
		margin-right: 20rpx;
	}

	.product-img image {
		width: 100%;
		height: 100%;
		border-radius: 8rpx;
		object-fit: cover;
	}

	.product-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.product-name {
		font-size: 30rpx;
		color: #333;
		line-height: 1.3;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
	}

	.product-spec {
		font-size: 26rpx;
		color: #999;
		margin-top: 10rpx;
	}

	.product-price {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-top: 10rpx;
	}

	.price {
		font-size: 30rpx;
		color: #f56c23;
		font-weight: bold;
	}

	.quantity {
		font-size: 26rpx;
		color: #999;
	}

	/* 配送信息样式 */
	.recipient {
		display: flex;
		align-items: center;
		margin-bottom: 15rpx;
	}

	.name {
		font-size: 30rpx;
		color: #333;
		margin-right: 20rpx;
	}

	.phone {
		font-size: 30rpx;
		color: #333;
	}

	.address {
		font-size: 28rpx;
		color: #666;
		line-height: 1.5;
		margin-bottom: 15rpx;
	}

	.delivery-method,
	.tracking-number {
		display: flex;
		align-items: center;
		margin-bottom: 15rpx;
	}

	.info-content {
		padding: 0 20rpx;
	}

	/* 价格信息样式 */
	.price-item {
		display: flex;
		align-items: center;
		padding: 20rpx;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.price-item:last-child {
		border-bottom: none;
	}

	.price-item.total .value {
		color: #f56c23;
		font-weight: bold;
		font-size: 32rpx;
	}

	/* 底部操作按钮组 */
	.order-actions {
		display: flex;
		justify-content: space-between;
		padding: 20rpx;
		background-color: white;
		margin: 20rpx;
		border-radius: 8rpx;
	}

	.order-actions button {
		flex: 1;
		margin: 0 10rpx;
		height: 88rpx;
		line-height: 88rpx;
		border-radius: 44rpx;
		font-size: 32rpx;
	}

	.popup-content {
		padding: 30rpx;
		box-sizing: border-box;

		h3 {
			font-size: 40rpx;
			margin-bottom: 20rpx;
		}

		.h3-1 {
			margin-top: 30rpx;
		}

		.items {
			min-height: 50rpx;
			font-size: 28rpx;
			color: #333;
			display: flex;
			align-items: center;
			padding: 10rpx 0;
			border-bottom: 1px solid #eee;

			input {
				width: 100%;
				height: 50rpx;
				font-size: 28rpx;
			}

			textarea {
				width: 100%;
				height: 150rpx;
			}
		}

		.btn {
			border: 1rpx solid #007AFF;
			color: #007AFF;
			width: 300rpx;
			border-radius: 20rpx;
			margin-top: 30rpx;
		}
	}
</style>